import XLSX from 'xlsx';
import ProTable from '@ant-design/pro-table';

export default function exportProtableToExcel(
  tableRef,
  fileName = '导出文件.xlsx',
  sheetName = '标签页1',
) {
  // 获取 Protable 的表格实例
  const tableInstance = tableRef.current;

  // 获取表格的列定义和数据
  const columns = tableInstance.columns;
  const dataSource = tableInstance.dataSource;

  // 将表格的列定义转换为 XLSX 库要求的格式
  const header = columns.map((column) => {
    return column.title;
  });

  // 将表格的数据转换为 XLSX 库要求的格式
  const data = dataSource.map((record) => {
    const rowData = {};
    columns.forEach((column) => {
      rowData[column.dataIndex] = record[column.dataIndex];
    });
    return rowData;
  });

  // 创建工作簿
  const wb = XLSX.utils.book_new();

  // 创建工作表
  const ws = XLSX.utils.json_to_sheet(data, { header });

  // 设置单元格的边框样式
  const range = XLSX.utils.decode_range(ws['!ref']);
  for (let rowNum = range.s.r; rowNum <= range.e.r; rowNum++) {
    for (let colNum = range.s.c; colNum <= range.e.c; colNum++) {
      const cellAddress = XLSX.utils.encode_cell({ r: rowNum, c: colNum });
      if (!ws[cellAddress]) {
        continue;
      }
      const cellStyle = {
        border: {
          top: { style: 'thin', color: { rgb: '000000' }, size: 1 },
          bottom: { style: 'thin', color: { rgb: '000000' }, size: 1 },
          left: { style: 'thin', color: { rgb: '000000' }, size: 1 },
          right: { style: 'thin', color: { rgb: '000000' }, size: 1 },
        },
      };
      ws[cellAddress].s = XLSXStyle.utils.build_style(cellStyle);
    }
  }

  // 将工作表添加到工作簿中
  XLSX.utils.book_append_sheet(wb, ws, sheetName);

  // 导出工作簿为 Excel 文件
  const wbout = XLSXStyle.write(wb, { bookType: 'xlsx', bookSST: true, type: 'binary' });
  saveAs(new Blob([s2ab(wbout)], { type: 'application/octet-stream' }), fileName);
}

// 字符串转ArrayBuffer
function s2ab(s) {
  const buf = new ArrayBuffer(s.length);
  const view = new Uint8Array(buf);
  for (let i = 0; i < s.length; i++) {
    view[i] = s.charCodeAt(i) & 0xff;
  }
  return buf;
}
